﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;


namespace DIProject
{
    public partial class FirstForm : Form
    {
        private int childFormNumber = 0;
        static private string _login = Environment.UserDomainName + "\\" + Environment.UserName;
        static string pswd = "test";
        static public string Login
        {
            get { return _login; }
            set { _login = value; }
        }
        private string  _password;

        public string  Password
        {
            get { return _password; }
            set { _password = value; }
        }

        public FirstForm()
        {
            InitializeComponent();
        }
        private bool CheckPassword()
        {
            frmPswd fp = new frmPswd();
            DialogResult dr = fp.ShowDialog(this);
            if (dr == DialogResult.OK)
            {
                string s = fp.Password;
                return s == pswd;
            }
            return false;
        }
        private void ShowNewForm(object sender, EventArgs e)
        {
          
        }

        private void OpenFile(object sender, EventArgs e)
        {
            
        }

        private void SaveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
        }

        private void ExitToolsStripMenuItem_Click(object sender, EventArgs e)
        {
            //Application.Exit();
            System.Diagnostics.Process.GetCurrentProcess().Kill();
        }

        private void CutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // TODO: Use System.Windows.Forms.Clipboard to insert the selected text or images into the clipboard
        }

        private void CopyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // TODO: Use System.Windows.Forms.Clipboard to insert the selected text or images into the clipboard
        }

        private void PasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // TODO: Use System.Windows.Forms.Clipboard.GetText() or System.Windows.Forms.GetData to retrieve information from the clipboard.
        }

        private void ToolBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
        }

        private void StatusBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
        }

        private void CascadeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.Cascade);
        }

        private void TileVerticleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileVertical);
        }

        private void TileHorizontalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileHorizontal);
        }

        private void ArrangeIconsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.ArrangeIcons);
        }

        private void CloseAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (System.Windows.Forms.Form childForm in MdiChildren)
            {
                childForm.Close();
            }
        }
       /* protected override void WndProc(ref Message m)
        {
            if (m.Msg == 0x3F)
                return;
            base.WndProc(ref m);
        }*/
        private void FarmGroup_Click(object sender, EventArgs e)
        {
            Dictionary.Catalog cat = new Dictionary.Catalog();
            cat.MdiParent = this;
            cat.Text = "Справочник фармацевтических групп";
            cat.Show();
        }
        public bool CheckLogin(string login, string password)
        {
           /* this.Login = login;
            this.Password = password;
            if (login == "test")
                return true;
            return false;*/
            string str = Properties.Settings.Default.DIAptekaConnectionString;
            string newString = Util.Login.RegonfigureConnectionString.Reconfire(str, login, password);
            FirstForm._login = login;
            Properties.Settings.Default["DIAptekaConnectionString"] = newString;
           // str = Properties.Settings.Default.DIAptekaConnectionString;
            string tmp = string.Empty;
            bool res = Util.Login.CheckLogin.Check(out tmp);
            if (!res)
            {
                MessageBox.Show("Ошибка авторизации\n" + tmp, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return res;
        }
        /// <summary>
        /// показываем только кассу или все.
        /// </summary>
        private bool CashOnly
        {
            get
            {
                string str = System.Configuration.ConfigurationManager.AppSettings["CashOnly"];
                if (string.IsNullOrEmpty(str))
                    return false;
                if (str == "1")
                    return true;
                return false;
            }
        }
        private void InitMenu()
        {
            if (!this.CashOnly)
            {
                for (Int32 i = 0; i < menuStrip.Items.Count; i++)
                {
                    switch (i)
                    {
                        case 1:
                        case 2:
                        case 4:
                        case 5:
                        case 6:
                            menuStrip.Items[i].Visible = false;
                            break;
                        default:
                            break;
                    }

                }
            }
        }
        private void MDIParent1_Load(object sender, EventArgs e)
        {
            Login lg = new Login(this);
           // lg.MdiParent = this;
            lg.ShowDialog();
            this.WindowState = FormWindowState.Maximized;
            this.InitMenu();
            this.pswdForReturnToolStripMenuItem.Visible = global::DIProject.Properties.Settings.Default.IsOffice;
        }

        private void оПрограммеToolStripMenuItem_Click(object sender, EventArgs e)
        {
           /* string str = "Операционная система\t" + Environment.OSVersion.ToString() +
                "\n" + "Пользователь\t" + Environment.UserDomainName + "\\" + Environment.UserName;
            MessageBox.Show(str);*/
            About a = new About();
            a.MdiParent = this;
            a.Show();
        }

        private void countryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Dictionary.Countries countries = new DIProject.Dictionary.Countries();
            countries.MdiParent = this;
            countries.Show();

        }

        private void ContragentsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Dictionary.Contragents contragents = new DIProject.Dictionary.Contragents();
            contragents.MdiParent = this;
            contragents.Show();
        }

        private void manufacturerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Dictionary.Manufacturers m = new DIProject.Dictionary.Manufacturers();
            m.MdiParent = this;
            m.Show();
        }

        private void medFormToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Dictionary.MedForm mf = new DIProject.Dictionary.MedForm();
            mf.MdiParent = this;
            mf.Show();
        }

        private void assortimentGroupToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Dictionary.AssessmentGroup ag = new DIProject.Dictionary.AssessmentGroup();
            ag.MdiParent = this;
            ag.Show();
        }

        private void AssortmentToolStripMenuItem_Click(object sender, EventArgs e)
        {
            /*Dictionary.Assortment ass = new DIProject.Dictionary.Assortment();
            ass.MdiParent = this;
            ass.Show();*/
            Dictionary.NewAssortment nas = new DIProject.Dictionary.NewAssortment();
            nas.MdiParent = this;
            nas.Show();
        }

        private void waybillsImportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ReceptionGoods.waybillsImport wi = new DIProject.ReceptionGoods.waybillsImport();
            wi.MdiParent = this;
            wi.Show();
        }

        private void CommonToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Setting.CommonSetting cs = new DIProject.Setting.CommonSetting();
            cs.MdiParent = this;
            cs.Show();
        }

        private void nkldListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ReceptionGoods.WaybillsImportList nkldList = new DIProject.ReceptionGoods.WaybillsImportList();
            nkldList.MdiParent = this;
            nkldList.Show();
		}

		private bool RefreshCashRegistersMenu(ToolStripMenuItem ownerItem, EventHandler click)
		{	ToolStripMenuItem menuItem;
			DataSets.Sales.CashRegisterCloseRow row;
			int		n = Sales.CloseCash.Sales.CashRegisterClose.Count	// количество открытых касс
				,	m = ownerItem.DropDownItems.Count					// количество пунктов меню
				,	k = Math.Min(n, m)
				,	i = 0
				;
		// Идём по существующим пунктам меню, меняем текст и тег
			for(; i < k; ++i)
			{	row = Sales.CloseCash.Sales.CashRegisterClose[i];
				menuItem		= (ToolStripMenuItem)ownerItem.DropDownItems[i];
				menuItem.Text	= row.name;
				menuItem.Tag	= row.shiftId;
			}
		// Добавляем новые пункты меню, назначаем текст, тег и обработчик события click
			for(; i < n; ++i)
			{	row = Sales.CloseCash.Sales.CashRegisterClose[i];
				menuItem		= new ToolStripMenuItem(row.name);
				menuItem.Tag	= row.shiftId;
				menuItem.Click	+= click;
				ownerItem.DropDownItems.Add(menuItem);
			}
		// Удаляем лишние пункты меню
			while(m-- > n)
				ownerItem.DropDownItems.RemoveAt(m);

			return n > 0;
		}

		private void SalesToolStripMenuItem_DropDownOpening(object sender, EventArgs e)
		{	bool canOpenClose	=	(int)CashReceiptToolStripMenuItem.Tag		== 0						// нет текущего чека
								&&	(int)CashReceiptReturnToolStripMenuItem.Tag	== 0						// нет текущего возврата
								;
			OpenCashToolStripMenuItem.Enabled	= canOpenClose && CloseCashToolStripMenuItem.Tag== null;	// и не закрывают кассу
			CloseCashToolStripMenuItem.Enabled	= canOpenClose && OpenCashToolStripMenuItem.Tag == null;	// и не открывают кассу

			bool	canCashOperate	=	canOpenClose														// нет текущих чека и возврата
									&&	OpenCashToolStripMenuItem.Tag	== null								// не открывают кассу
									&&	CloseCashToolStripMenuItem.Tag	== null								// не закрывают кассу
				,	canReceipt		= canCashOperate
				,	canReceiptReturn= canCashOperate
				;
			if(canCashOperate)
			{	Sales.CloseCash.CashRegisterCloseTableAdapter.Fill(Sales.CloseCash.Sales.CashRegisterClose,  Util.CashRecorder.SerialNumber);

			// Новый чек по кассам
				canReceipt = RefreshCashRegistersMenu(CashReceiptToolStripMenuItem, new EventHandler(CashReceiptToolStripMenuItem_Click));

			// Возвраты чеков по кассам
				canReceiptReturn = RefreshCashRegistersMenu(CashReceiptReturnToolStripMenuItem, new EventHandler(CashReceiptReturnToolStripMenuItem_Click));
			}
			CashReceiptToolStripMenuItem.Enabled		= canReceipt;
			CashReceiptReturnToolStripMenuItem.Enabled	= canReceiptReturn;
		}

		private void CashReceiptToolStripMenuItem_Click(object sender, EventArgs e)
		{	ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
			if(menuItem.Tag is DIProject.Sales.CashReceipt)
				((DIProject.Sales.CashReceipt)menuItem.Tag).Activate();
			else
			{	DIProject.Sales.CashReceipt cashReceipt = new DIProject.Sales.CashReceipt(menuItem);
				cashReceipt.MdiParent = this;
				cashReceipt.Show();
			}
		}

		private void CashReceiptReturnToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Sales.ReturnPassword rp = new DIProject.Sales.ReturnPassword();
            DialogResult dr = rp.ShowDialog();
            if (dr == DialogResult.OK)
            {
                string str = rp.txbPassword.Text;
                Int32 deptId = Data.Department.CurrentDepartment;
                string str2 = Util.Setting.GetCashPassword(deptId);
                str = Util.Setting.GetHash(str);
                if (str != str2)
                {
                    MessageBox.Show("Неверный пароль");
                    return;
                }
            }
            else
            {
                return;
            }
            ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
			if(menuItem.Tag is DIProject.Sales.CashReceiptReturn)
				((DIProject.Sales.CashReceiptReturn)menuItem.Tag).Activate();
			else
			{	DIProject.Sales.CashReceiptReturn cashReceiptReturn = new DIProject.Sales.CashReceiptReturn(menuItem);
				cashReceiptReturn.MdiParent = this;
				cashReceiptReturn.Show();
			}
		}

        private void CustomerReturnToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Sales.ReturnPassword rp = new DIProject.Sales.ReturnPassword();
            DialogResult dr = rp.ShowDialog();
            if (dr == DialogResult.OK)
            {
                string str = rp.txbPassword.Text;
                Int32 deptId = Data.Department.CurrentDepartment;
                string str2 = Util.Setting.GetCashPassword(deptId);
                str = Util.Setting.GetHash(str);
                if (str != str2)
                {
                    MessageBox.Show("Неверный пароль");
                    return;
                }
            }
            else
            {
                return;
            }
            ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
            if (menuItem.Tag is DIProject.Sales.CustomerReturn)
                ((DIProject.Sales.CustomerReturn)menuItem.Tag).Activate();
            else
            {
                DIProject.Sales.CustomerReturn customerReturn = new DIProject.Sales.CustomerReturn(menuItem);
                customerReturn.MdiParent = this;
                customerReturn.Show();
            }
        }

		private void OpenCashToolStripMenuItem_Click(object sender, EventArgs e)
		{	ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
			if(menuItem.Tag is DIProject.Sales.OpenCash)
				((DIProject.Sales.OpenCash)menuItem.Tag).Activate();
			else
			{	DIProject.Sales.OpenCash openCash = new DIProject.Sales.OpenCash(menuItem);
				openCash.MdiParent = this;
				openCash.Show();
			}
		}

		private void CloseCashToolStripMenuItem_Click(object sender, EventArgs e)
		{	ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
			if(menuItem.Tag is DIProject.Sales.CloseCash)
				((DIProject.Sales.CloseCash)menuItem.Tag).Activate();
			else
			{	DIProject.Sales.CloseCash closeCash = new DIProject.Sales.CloseCash(menuItem);
				closeCash.MdiParent = this;
				closeCash.Show();
			}
		}

		private void checksToolStripMenuItem_Click(object sender, EventArgs e)
		{	ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
			if(menuItem.Tag is DIProject.Sales.Checks)
				((DIProject.Sales.Checks)menuItem.Tag).Activate();
			else
			{	DIProject.Sales.Checks checks = new DIProject.Sales.Checks(menuItem);
				checks.MdiParent = this;
				checks.Show();
			}
		}

		private void checkReturnsToolStripMenuItem_Click(object sender, EventArgs e)
		{	ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
			if(menuItem.Tag is DIProject.Sales.CheckReturns)
				((DIProject.Sales.CheckReturns)menuItem.Tag).Activate();
			else
			{	DIProject.Sales.CheckReturns checkReturns = new DIProject.Sales.CheckReturns(menuItem);
				checkReturns.MdiParent = this;
				checkReturns.Show();
			}
		}

        private void catalogTreeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Dictionary.CatalogTree catTree = new DIProject.Dictionary.CatalogTree();
            catTree.MdiParent = this;
            catTree.Show();
        }

		private void shiftOutToolStripMenuItem_Click(object sender, EventArgs e)
		{	ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
			if(menuItem.Tag is DIProject.Stock.ShiftsOut)
				((DIProject.Stock.ShiftsOut)menuItem.Tag).Activate();
			else
			{	DIProject.Stock.ShiftsOut shiftsOut = new DIProject.Stock.ShiftsOut(menuItem);
				shiftsOut.MdiParent = this;
				shiftsOut.Show();
			}
		}

		private void shiftInToolStripMenuItem_Click(object sender, EventArgs e)
        {
        //{	ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
        //    if(menuItem.Tag is DIProject.Stock.ShiftsIn)
        //        ((DIProject.Stock.ShiftsIn)menuItem.Tag).Activate();
        //    else
        //    {	DIProject.Stock.ShiftsIn shiftsIn = new DIProject.Stock.ShiftsIn(menuItem);
        //        shiftsIn.MdiParent = this;
        //        shiftsIn.Show();
        //    }
            DIProject.Stock.ShiftsIn shiftsIn = new DIProject.Stock.ShiftsIn();// (menuItem);
            shiftsIn.MdiParent = this;
            shiftsIn.Show();
		}

		private void repriceToolStripMenuItem_Click(object sender, EventArgs e)
		{	ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
			if(menuItem.Tag is DIProject.Stock.Reprices)
				((DIProject.Stock.Reprices)menuItem.Tag).Activate();
			else
			{	DIProject.Stock.Reprices reprices = new DIProject.Stock.Reprices(menuItem);
				reprices.MdiParent = this;
				reprices.Show();
			}
		}

		private void disgatherToolStripMenuItem_Click(object sender, EventArgs e)
		{	ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
			if(menuItem.Tag is DIProject.Stock.Disgathers)
				((DIProject.Stock.Disgathers)menuItem.Tag).Activate();
			else
			{	DIProject.Stock.Disgathers disgathers = new DIProject.Stock.Disgathers(menuItem);
				disgathers.MdiParent = this;
				disgathers.Show();
			}
		}

		private void writeOffToolStripMenuItem_Click(object sender, EventArgs e)
		{	ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
			if(menuItem.Tag is DIProject.Stock.WriteOffs)
				((DIProject.Stock.WriteOffs)menuItem.Tag).Activate();
			else
			{	DIProject.Stock.WriteOffs writeOffs = new DIProject.Stock.WriteOffs(menuItem);
				writeOffs.MdiParent = this;
				writeOffs.Show();
			}
		}

		private void supplierReturnToolStripMenuItem_Click(object sender, EventArgs e)
		{	ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
			if(menuItem.Tag is DIProject.ReceptionGoods.SupplierReturns)
				((DIProject.ReceptionGoods.SupplierReturns)menuItem.Tag).Activate();
			else
			{	DIProject.ReceptionGoods.SupplierReturns supplierReturns = new DIProject.ReceptionGoods.SupplierReturns(menuItem);
				supplierReturns.MdiParent = this;
				supplierReturns.Show();
			}
		}

        private void toolStripMenuItem_Click(ToolStripMenuItem menuItem, string dllName, string formTypeName)
        {
            string s = AppDomain.CurrentDomain.BaseDirectory + dllName;
            System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, formTypeName);
            IntegrationInterface.IDIProjectForm i = f.Unwrap() as IntegrationInterface.IDIProjectForm;
            if (i != null)
            {
                i.ConnectionString = Properties.Settings.Default.DIAptekaConnectionString;
                i.Login = Login;
                i.CommonProperty = menuItem;

                System.Windows.Forms.Form ff = i.MailForm;
                ff.MdiParent = this;
                ff.Show();

            }

        }

        void i_UnloadOrders(object sender, EventArgs e)
        {
            string docNum = (string)sender;
            if(string.IsNullOrEmpty(docNum))
                throw new Exception("Не определен номер документа");
            string[] mStr = docNum.Split(new char[] { ':' });
            if (mStr.Length != 2)
                throw new Exception("Неправильный формат строки");
            Int32 deptId;
            if (!Int32.TryParse(mStr[1], out deptId))
                throw new Exception("Требуется целое число");
            Util.Orders.OrdersUnload unl = new DIProject.Util.Orders.OrdersUnload();
            unl.Unload(mStr[0],deptId);
        }

        void i_LoadPrices(object sender, EventArgs e)
        {         
            Util.Orders.PricesLoad pl = new DIProject.Util.Orders.PricesLoad();
            System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(pl.Load));
            t.Start();            
        }

        void i_CallNewGoods(object sender, EventArgs e)
        {
            Dictionary.NewGoods ng = new DIProject.Dictionary.NewGoods();
            //System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ng));
            //t.Start();
            ng.ShowDialog();
        }

        private void goodsOrderToolStripMenuItem_Click(object sender, EventArgs e)
		{
            try
            {
                string s = AppDomain.CurrentDomain.BaseDirectory + "Orders.dll";
                System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "DIProject.ReceptionGoods.Orders");
                IntegrationInterface.IDIProjectForm2 i = f.Unwrap() as IntegrationInterface.IDIProjectForm2;
                if (i != null)
                {
                    i.ConnectionString = Properties.Settings.Default.DIAptekaConnectionString;
                    i.Login = Login;
                    i.LoadPrices += new EventHandler(i_LoadPrices);
                    i.UnloadOrders += new EventHandler(i_UnloadOrders);                   
                    i.CommonEvent += new EventHandler<IntegrationInterface.DIEventArgs>(i_CommonEvent);                    
                    System.Windows.Forms.Form ff = i.MailForm;
                    ff.MdiParent = this;
                    ff.Show();
                }
            }
            catch (Exception ee)
            {
                string s = ee.ToString();
                throw ee;
            }
        }
        #region обработка общих событий
        private void NewGoodsShow()
        {
            Dictionary.NewGoods ng = new DIProject.Dictionary.NewGoods();
            ng.Show();
        }
        private void CallChangeRecode(string s)
        {
            Dictionary.Link l = new DIProject.Dictionary.Link();
            l.startuptext = s;
            l.MdiParent = this;
            l.Show();        
        }
        #endregion
        void i_CommonEvent(object sender, IntegrationInterface.DIEventArgs e)
        {
            switch (e.CommandName)
            {
                case "NewGoodsShow":
                    NewGoodsShow();
                    break;
                case "CallChangeRecode": // Вызываем изменение перекодировок
                    string s = (string)e.Params["PricePosName"];
                    CallChangeRecode(s);                    
                    break;
                default:
                    throw new Util.DIException("Не задана команда для события");
            }
        }

		private void syncToolStripMenuItem_Click(object sender, EventArgs e)
		{	
            toolStripMenuItem_Click((ToolStripMenuItem)sender, "Sync.dll", "DIProject.Sync.SyncInfos");
		}

		private void export_1C(ToolStripMenuItem menuItem, string formTypeName)
		{	toolStripMenuItem_Click(menuItem, "Export_1C.dll", formTypeName);
		}
		private void accountsToolStripMenuItem_Click(object sender, EventArgs e)
		{	export_1C((ToolStripMenuItem)sender, "DIProject.Export_1C.LedgerAccounts");
		}

		private void subcontoToolStripMenuItem_Click(object sender, EventArgs e)
		{	export_1C((ToolStripMenuItem)sender, "DIProject.Export_1C.LedgerSubcontoTypes");
		}

		private void transTypesToolStripMenuItem_Click(object sender, EventArgs e)
		{	export_1C((ToolStripMenuItem)sender, "DIProject.Export_1C.LedgerTransTypes");
		}

		private void operationsToolStripMenuItem_Click(object sender, EventArgs e)
		{	export_1C((ToolStripMenuItem)sender, "DIProject.Export_1C.LedgerOperations");
		}

		private void transTypesOperationsToolStripMenuItem_Click(object sender, EventArgs e)
		{	export_1C((ToolStripMenuItem)sender, "DIProject.Export_1C.LedgerTransTypesOperations");
		}

		private void doExportToolStripMenuItem_Click(object sender, EventArgs e)
		{	MessageBox.Show(this, "В разработке");
		}

        private void ZCFormToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ReceptionGoods.SZForm szf = new DIProject.ReceptionGoods.SZForm();
            szf.MdiParent = this;
            szf.Show();
        }

        private void goodsToolStripMenuItem_Click(object sender, EventArgs e)
        {
           /* Dictionary.Goods g = new DIProject.Dictionary.Goods();
            g.MdiParent = this;
            g.Show();*/
            Dictionary.NewGoods ng = new DIProject.Dictionary.NewGoods();
            ng.MdiParent = this;
            ng.Show();
        }

        private void CashReceiptToolStripMenuItem_Click_1(object sender, EventArgs e)
        {

        }

        private void PartiesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ReceptionGoods.PartiesForm pf = new DIProject.ReceptionGoods.PartiesForm();
            pf.MdiParent = this;
            pf.Show();
        }

        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            /*ReceptionGoods.QuotationGoods g = new DIProject.ReceptionGoods.QuotationGoods();
            g.MdiParent = this;
            g.Show();*/
        }

        private void currentPrtyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
        }

        private void GoodsTransferToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (CheckPassword())
            {
                string s = Environment.CurrentDirectory + "\\Reports.dll";
                string GoodsTransferPath = System.Configuration.ConfigurationManager.AppSettings["GoodsTransfer"];
                //System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "Reports.TurnoverBook.InputParamForm");
                System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "Reports.GoodsTransfer.InputParamForm");
                IntegrationInterface.IDIProjectForm i = f.Unwrap() as IntegrationInterface.IDIProjectForm;
                if (i != null)
                {
                    i.ConnectionString = Properties.Settings.Default.DIAptekaConnectionString;
                    i.CommonProperty = GoodsTransferPath;
                    System.Windows.Forms.Form ff = i.MailForm;
                    ff.MdiParent = this;
                    ff.Show();
                }
            }
        }

        private void TurnoverBookToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (CheckPassword())
            {
                string s = Environment.CurrentDirectory + "\\Reports.dll";
                string TurnoverBook = System.Configuration.ConfigurationManager.AppSettings["TurnoverBook"];
                System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "Reports.TurnoverBook.InputParamForm");
                //System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "Reports.GoodsTransfer.InputParamForm");
                IntegrationInterface.IDIProjectForm i = f.Unwrap() as IntegrationInterface.IDIProjectForm;
                if (i != null)
                {
                    i.ConnectionString = Properties.Settings.Default.DIAptekaConnectionString;
                    i.CommonProperty = TurnoverBook;
                    System.Windows.Forms.Form ff = i.MailForm;
                    ff.MdiParent = this;
                    ff.Show();
                }
            }
        }

        private void RestToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (CheckPassword())
            {
                string s = Environment.CurrentDirectory + "\\Reports.dll";
                string Rest = System.Configuration.ConfigurationManager.AppSettings["Rest"];
                System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "Reports.Rest.InputParamForm");
                //System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "Reports.GoodsTransfer.InputParamForm");
                object o = f.Unwrap();
                IntegrationInterface.IDIProjectForm i = o as IntegrationInterface.IDIProjectForm;
                if (i != null)
                {
                    i.ConnectionString = Properties.Settings.Default.DIAptekaConnectionString;
                    i.CommonProperty = Rest;
                    System.Windows.Forms.Form ff = i.MailForm;
                    ff.MdiParent = this;
                    // IntegrationInterface.IDIReport r = o as IntegrationInterface.IDIReport;
                    // r.InitReport(Rest);
                    ff.Show();
                }
            }
        }

        private void OptCashIncomeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (CheckPassword())
            {
                string s = Environment.CurrentDirectory + "\\Reports.dll";
                string RoznCashIncome = System.Configuration.ConfigurationManager.AppSettings["RoznCashIncome"];
                System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "Reports.RoznCashIncome.InputParamForm");
                //System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "Reports.GoodsTransfer.InputParamForm");
                IntegrationInterface.IDIProjectForm i = f.Unwrap() as IntegrationInterface.IDIProjectForm;
                if (i != null)
                {
                    i.ConnectionString = Properties.Settings.Default.DIAptekaConnectionString;
                    i.CommonProperty = RoznCashIncome;
                    System.Windows.Forms.Form ff = i.MailForm;
                    ff.MdiParent = this;
                    ff.Show();
                }
            }
        }

        private void IncomeBookToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (CheckPassword())
            {
                string s = Environment.CurrentDirectory + "\\Reports.dll";
                string IncomeBook = System.Configuration.ConfigurationManager.AppSettings["IncomeBook"];
                System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "Reports.IncomeBook.InputParamForm");
                //System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "Reports.GoodsTransfer.InputParamForm");
                IntegrationInterface.IDIProjectForm i = f.Unwrap() as IntegrationInterface.IDIProjectForm;
                if (i != null)
                {
                    i.ConnectionString = Properties.Settings.Default.DIAptekaConnectionString;
                    i.CommonProperty = IncomeBook;
                    System.Windows.Forms.Form ff = i.MailForm;
                    ff.MdiParent = this;
                    ff.Show();
                }
            }
        }

        private void OptDocIncomeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (CheckPassword())
            {
                string s = Environment.CurrentDirectory + "\\Reports.dll";
                string OptDocIncome = System.Configuration.ConfigurationManager.AppSettings["OptDocIncome"];
                System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "Reports.OptDocIncome.InputParamForm");
                //System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "Reports.GoodsTransfer.InputParamForm");
                IntegrationInterface.IDIProjectForm i = f.Unwrap() as IntegrationInterface.IDIProjectForm;
                if (i != null)
                {
                    i.ConnectionString = Properties.Settings.Default.DIAptekaConnectionString;
                    i.CommonProperty = OptDocIncome;
                    System.Windows.Forms.Form ff = i.MailForm;
                    ff.MdiParent = this;
                    ff.Show();
                }
            }
        }

        private void PurchaseBookToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (CheckPassword())
            {
                string s = Environment.CurrentDirectory + "\\Reports.dll";
                string PurchaseBook = System.Configuration.ConfigurationManager.AppSettings["PurchaseBook"];
                System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "Reports.PurchaseBook.InputParamForm");
                //System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "Reports.GoodsTransfer.InputParamForm");
                IntegrationInterface.IDIProjectForm i = f.Unwrap() as IntegrationInterface.IDIProjectForm;
                if (i != null)
                {
                    i.ConnectionString = Properties.Settings.Default.DIAptekaConnectionString;
                    i.CommonProperty = PurchaseBook;
                    System.Windows.Forms.Form ff = i.MailForm;
                    ff.MdiParent = this;
                    ff.Show();
                }
            }
        }

        private void SalesBookToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string s = Environment.CurrentDirectory + "\\Reports.dll";
            string SalesBook = System.Configuration.ConfigurationManager.AppSettings["SalesBook"];
            System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "Reports.SalesBook.InputParamForm");
            //System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "Reports.GoodsTransfer.InputParamForm");
            IntegrationInterface.IDIProjectForm i = f.Unwrap() as IntegrationInterface.IDIProjectForm;
            if (i != null)
            {
                i.ConnectionString = Properties.Settings.Default.DIAptekaConnectionString;
                i.CommonProperty = SalesBook;
                System.Windows.Forms.Form ff = i.MailForm;
                ff.MdiParent = this;
                ff.Show();
            }
        }

        private void GoodsReportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //GoodsReport
            if (CheckPassword())
            {
                string s = Environment.CurrentDirectory + "\\Reports.dll";
                string GoodsReport = System.Configuration.ConfigurationManager.AppSettings["GoodsReport"];
                System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "Reports.GoodsReport.InputParamForm");
                //System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "Reports.GoodsTransfer.InputParamForm");
                IntegrationInterface.IDIProjectForm i = f.Unwrap() as IntegrationInterface.IDIProjectForm;
                if (i != null)
                {
                    i.ConnectionString = Properties.Settings.Default.DIAptekaConnectionString;
                    i.CommonProperty = GoodsReport;
                    System.Windows.Forms.Form ff = i.MailForm;
                    ff.MdiParent = this;
                    ff.Show();
                }
            }
        }

        private void RoznDocIncomeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //RoznDocIncome
            if (CheckPassword())
            {
                string s = Environment.CurrentDirectory + "\\Reports.dll";
                string RoznDocIncome = System.Configuration.ConfigurationManager.AppSettings["RoznDocIncome"];
                System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "Reports.RoznDocIncome.InputParamForm");
                //System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "Reports.GoodsTransfer.InputParamForm");
                IntegrationInterface.IDIProjectForm i = f.Unwrap() as IntegrationInterface.IDIProjectForm;
                if (i != null)
                {
                    i.ConnectionString = Properties.Settings.Default.DIAptekaConnectionString;
                    i.CommonProperty = RoznDocIncome;
                    System.Windows.Forms.Form ff = i.MailForm;
                    ff.MdiParent = this;
                    ff.Show();
                }
            }
        }

        private void LinksToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Dictionary.Link l = new DIProject.Dictionary.Link();
            l.MdiParent = this;
            l.Show();
        }

        private void usersToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Dictionary.DepartmentUsers du = new DIProject.Dictionary.DepartmentUsers();
            du.MdiParent = this;
            du.Show();
        }

        private void чисткаToolStripMenuItem_Click(object sender, EventArgs e)
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
        }

        private void curPartiesToolStripMenuItem_Click(object sender, EventArgs e)
        {
           
        }

        private void curOstToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Sales.SmallPartiesList spl = new DIProject.Sales.SmallPartiesList();
            spl.MdiParent = this;
            spl.Show();
        }

        private void RestOstToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DIProject.Sales.PartiesList pl = new DIProject.Sales.PartiesList();
            pl.MdiParent = this;
            pl.Show();
        }

        private void pswdForReturnToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DIProject.Setting.CashPassword cp = new DIProject.Setting.CashPassword();
            DialogResult dr = cp.ShowDialog();
            if (dr == DialogResult.OK || dr == DialogResult.Cancel)
            {
                cp.Close();
            }
        }

        private void goodsTransver2ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //if (CheckPassword())
            {
                string s = Environment.CurrentDirectory + "\\Reports.dll";
                string GoodsTransfer2 = System.Configuration.ConfigurationManager.AppSettings["GoodsTransfer2"];
                System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "Reports.YULIA.NewGoodsReport");
                IntegrationInterface.IDIProjectForm i = f.Unwrap() as IntegrationInterface.IDIProjectForm;
                if (i != null)
                {
                    i.ConnectionString = Properties.Settings.Default.DIAptekaConnectionString;
                    i.CommonProperty = GoodsTransfer2;
                    System.Windows.Forms.Form ff = i.MailForm;
                    ff.MdiParent = this;
                    ff.Show();
                }
            }
        }

        private void esfiToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string s = Environment.CurrentDirectory + "\\ReCode.dll";
            System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "ReCode.PriceRowsNotParsed");
            IntegrationInterface.IDIProjectForm i = f.Unwrap() as IntegrationInterface.IDIProjectForm;
            if (i != null)
            {
                i.ConnectionString = Properties.Settings.Default.DIAptekaConnectionString;
                System.Windows.Forms.Form ff = i.MailForm;
                ff.MdiParent = this;
                ff.Show();
            }
        }

        private void esfiUnloadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("Выгрузить текущий прайс в ЕСФИ?", "Выгрузка прайса", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr != DialogResult.OK)
                return;
            ToESFI.ESFIUnloader u = new ToESFI.ESFIUnloader();
            u.ConnectionString = Properties.Settings.Default.DIAptekaConnectionString;
            u.Path = DIProject.Util.Esfi.ESFIPath;
            DataTable dt = u.GetData(Util.Esfi.ESFIID, Util.Esfi.ESFIOrg_ID);
            u.SaveData(dt);
            MessageBox.Show("Данные успешно выгружены", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void PriceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ReCode.Util.Common.ConnectionString = Properties.Settings.Default.DIAptekaConnectionString;
            ReCode.NotParsedLineForm f = new ReCode.NotParsedLineForm();
            f.MdiParent = this;
            f.Show();
        }
        /// <summary>
        /// сроки годности
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExpiredToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string s = Environment.CurrentDirectory + "\\Reports.dll";
            string WorkingLives = System.Configuration.ConfigurationManager.AppSettings["WorkingLives"];
            System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "Reports.WorkingLives.InputParamForm");
            //System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "Reports.GoodsTransfer.InputParamForm");
            IntegrationInterface.IDIProjectForm i = f.Unwrap() as IntegrationInterface.IDIProjectForm;
            if (i != null)
            {                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
                i.ConnectionString = Properties.Settings.Default.DIAptekaConnectionString;
                i.CommonProperty = WorkingLives;
                System.Windows.Forms.Form ff = i.MailForm;
                ff.MdiParent = this;
                ff.Show();
            }
        }

        private void ExportFarmgradToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Ерундень.
            string s = Environment.CurrentDirectory + "\\Export2SST.dll";
            System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "Export2SST.Export2SSTForm");            
            IntegrationInterface.IDIProjectForm i = f.Unwrap() as IntegrationInterface.IDIProjectForm;
            if (i != null)
            {
                i.ConnectionString = Properties.Settings.Default.DIAptekaConnectionString;                
                System.Windows.Forms.Form ff = i.MailForm;
                ff.MdiParent = this;
                ff.Show();
            }
        }

        private void NewCheckstoolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Здесь будет вызов новой формы чеков со всеми прибабахами
            string s = Environment.CurrentDirectory + "\\NewChecks.dll";
            System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "NewChecks.Sales.CheksForm");
            IntegrationInterface.IDIProjectForm i = f.Unwrap() as IntegrationInterface.IDIProjectForm;
            if (i != null)
            {
                i.ConnectionString = Properties.Settings.Default.DIAptekaConnectionString;
                System.Windows.Forms.Form ff = i.MailForm;
                ff.MdiParent = this;
                ff.Show();
            }
        }

        private void LoadDRUGSToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Здесь будет вызов новой формы чеков со всеми прибабахами
            string s = Environment.CurrentDirectory + "\\LoadDRUGS.dll";
            System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "LoadSST.LoadSSTForm");
            IntegrationInterface.IDIProjectForm i = f.Unwrap() as IntegrationInterface.IDIProjectForm;
            if (i != null)
            {
                i.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\TEMP;Extended Properties=dBASE IV;User ID=Admin;Password=";
                i.CommonProperty = Properties.Settings.Default.DIAptekaConnectionString;
                System.Windows.Forms.Form ff = i.MailForm;
                ff.MdiParent = this;
                ff.Show();
            }
        }

        private void ServicetoolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void SumSkladtoolStripMenuItem_Click(object sender, EventArgs e)
        {
            ReceptionGoods.SkladSumReportForm ssrf = new DIProject.ReceptionGoods.SkladSumReportForm();
            ssrf.Show();
        }

        private void openclosecashToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Reports.OpenCloseCashForm occform = new DIProject.Reports.OpenCloseCashForm();
            occform.Show();
        }

        private void WaybillSum_Click(object sender, EventArgs e)
        {
            ReceptionGoods.WaybillsSumForm form = new ReceptionGoods.WaybillsSumForm();
            form.MdiParent = this;
            form.Show();
        }
    }
}
